<template>
    <div class="content-wrapper-view">
        <div class="content-wrapper-body">
            <!-- 开始 -->
            <!-- 工具栏- -->
            <div class="filter-wrapper">
                <el-form ref="filterForm" :model="listQuery" :inline="true">

                    <el-form-item size="medium">
                        <el-cascader
                            clearable
                            :options="categoryOptions"
                            :props="defaultProps"
                            v-model="categoryIds"
                            @change="handleChangeCascader"
                            placeholder="商品分类" 
                            style="width: 300px"
                            >
                        </el-cascader>
                    </el-form-item>

                    <el-form-item prop="brandId" size="medium">
                        <el-select v-model="listQuery.brandId" clearable placeholder="商品品牌" style="width: 100%">
                            <el-option
                                    v-for="item in brandOptions"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item prop="typeId" size="medium">
                        <el-select v-model="listQuery.typeId" clearable placeholder="商品类型" style="width: 100%">
                            <el-option
                                    v-for="item in typeOptions"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item prop="name" size="medium">
                        <el-input v-model="listQuery.name" placeholder="关键字"></el-input>
                    </el-form-item>

                    <el-form-item prop="status" size="medium">
                        <el-select v-model="listQuery.status" placeholder="状态" clearable style="width: 100px">
                            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-button type="primary" size="medium" icon="el-icon-search" @click="handleFilter">搜索</el-button>
                    <el-button type="primary" size="medium" icon="el-icon-mars-reset" @click="handleResetFilter">重置</el-button>
                    <el-button v-if="authorize('system:mallgoodsspecattr:add')" type="primary" size="medium" icon="el-icon-plus" @click="handleCreate">添加</el-button>
                    <el-button v-if="authorize('system:mallgoodsspecattr:delete')" type="danger" size="medium" icon="el-icon-delete" @click="handleDelete">批量删除</el-button>
                </el-form>
            </div>

            <!-- 表格 -->
            <el-table 
                border fit highlight-current-row 
                v-loading="listLoading" 
                ref="table"
                :data="list" 
                element-loading-text="给我一点时间" 
                @selection-change="handleSelectionChange">

                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column type="index" width="55" align="center"></el-table-column>

                <el-table-column label="分类" align="center" width="120">
                    <template slot-scope="scope"> {{ scope.row.category ? scope.row.category.name : '-' }} </template>
                </el-table-column>
                <el-table-column label="品牌" align="center" width="120">
                    <template slot-scope="scope"> {{ scope.row.brand ? scope.row.brand.name : '-' }} </template>
                </el-table-column>
                <el-table-column label="类型" align="center" width="120">
                    <template slot-scope="scope"> {{ scope.row.type ? scope.row.type.name : '-' }} </template>
                </el-table-column>
                <el-table-column label="规格" align="center">
                    <template slot-scope="scope"> 
                        <el-tag type="primary">{{ scope.row.name }} </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="排序" align="center" width="80">
                    <template slot-scope="scope"> {{ scope.row.sort }} </template>
                </el-table-column>
                <el-table-column label="创建时间" align="center" width="160">
                    <template slot-scope="scope"> {{scope.row.ctime | parseTime('{y}-{m}-{d} {h}:{i}:{s}')}} </template>
                </el-table-column>
                <el-table-column label="最后更新时间" align="center" width="160">
                    <template slot-scope="scope"> {{scope.row.utime | parseTime('{y}-{m}-{d} {h}:{i}:{s}')}} </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button v-if="authorize('mallgoodsspecattr:update')" size="small" type="primary" icon="edit" @click="handleUpdate(scope.row)">编辑</el-button>
                        <el-button v-if="authorize('mallgoodsspecattr:delete')" size="small" type="danger" icon="delete" @click="handleDelete(scope.row)">删除</el-button>
                        <el-button v-if="authorize('mallgoodsspecattr:delete')" size="small" type="primary" icon="delete" @click="handleSpecVal(scope.row)">管理规格值</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页工具栏 -->
            <div v-if="!listLoading" class="pagination-container">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page" :page-sizes="[10, 20, 30, 50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
                </el-pagination>
            </div>

            <!-- 窗口 -->
            <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" @close="handleDialogClose">
                <el-form ref="form" :model="form" :rules="rules" label-width="120px">

                    <el-form-item label="所属商品分类">
                        <el-cascader
                            clearable
                            :options="categoryOptions"
                            :props="defaultProps"
                            v-model="categoryIds"
                            @change="handleChangeCascader"
                            placeholder="请选择分类" style="width: 80%"
                            >
                        </el-cascader>
                    </el-form-item>

                    <el-form-item label="所属商品品牌">
                        <el-select v-model="form.brandId" clearable placeholder="请选择品牌" style="width: 80%">
                            <el-option
                                    v-for="item in brandOptions"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="所属商品类型">
                        <el-select v-model="form.typeId" clearable placeholder="请选择类型" style="width: 100%">
                            <el-option
                                    v-for="item in typeOptions"
                                    :key="item.id"
                                    :label="item.name"
                                    :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="商品规格" prop="name">
                        <el-input v-model="form.name" placeholder="商品规格属性" style="width: 80%;"></el-input>
                    </el-form-item>
                    <el-form-item label="排序">
                        <el-input-number v-model="form.sort" :min="99" :max="99999"></el-input-number>
                    </el-form-item>

                </el-form>

                <div slot="footer" class="dialog-footer">
                    <el-button @click="cancel('form')">取 消</el-button>
                    <el-button v-if="dialogStatus == 'create'" type="primary" @click="create('form')">确 定</el-button>
                    <el-button v-else type="primary" @click="update('form')">确 定</el-button>
                </div>
            </el-dialog>

        </div>
        <back-to-top></back-to-top>
    </div>
</template>

<script>
import {
    createdSpecAttr,
    updatedSpecAttr,
    deletedSpecAttr,
    selectOneSpecAttr,
    selectListSpecAttr,
    selectPageSpecAttr,
    selectPageAssociationCategoryAndBrandAndType
} from "@/api/mall/GoodsSpecAttr";
import { selectTree } from '@/api/mall/GoodsCategory'
import { selectList as selectListBrand } from '@/api/mall/GoodsBrand'
import { selectList as selectListType } from '@/api/mall/GoodsType'
import { ResultMessage } from "@/libs/response";
import { isAuth } from "@/libs/auth";
import BackToTop from "@/components/BackToTop/index";
import valid from "@/libs/rules";

const statusOptions = [
    { label: "正常", value: true },
    { label: "锁定", value: false }
];

export default {
    name: "MallGoodsSpecAttr",
    components: { BackToTop },
    data() {
        let required = valid.required();
        return {
            list: null,
            total: null,
            listLoading: true,
            listQuery: {
                page: 1,
                limit: 10,
                name: null,
                categoryId: null,
                brandId: null,
                typeId: null
            },
            form: {
                categoryId: null,
                categoryIds: null,
                sort: 99
            },
            rules: {
                example: [required]
            },

            multipleSelection: [],
            statusOptions,
            dialogFormVisible: false,
            dialogStatus: "",
            textMap: { update: "编辑", create: "创建" },

            categoryIds: [],
            categoryOptions: [],
            defaultProps: {
                label: "name",
                value: "id",
                children: "children"
            },

            brandOptions: [],
            typeOptions: []
        };
    },
    created() {
        this.getGoodsCategory()
        this.getGoodsBrand()
        this.getGoodsType()
        this.getPage();
    },
    methods: {
        authorize(auth) {
            return isAuth(auth); //按钮权限验证
        },
        handleFilter() {
            //条件过滤
            this.listQuery.page = 1;
            this.getPage();
        },
        handleResetFilter() {
            //重置过滤条件
            this.cancel("filterForm");
            //this.listQuery.categoryId = null
            //this.categoryIds = []
            this.getPage();
        },
        handleDialogClose() {
            //关闭窗口回调函数
            this.cancel("form");
            //this.categoryIds = []
        },
        handleSelectionChange(val) {
            //多选
            this.multipleSelection = val;
        },
        handleSizeChange(val) {
            this.listQuery.page = 1;
            this.listQuery.limit = val;
            this.getPage();
        },
        handleCurrentChange(val) {
            this.listQuery.page = val;
            this.getPage();
        },
        handleCreate() {
            //添加数据窗口
            this.dialogStatus = "create";
            this.dialogFormVisible = true;
            
        },
        handleUpdate(row) {
            //修改数据窗口
            this.getData(row.id).then(response => {
                if (response) {
                    this.dialogStatus = "update";
                    this.dialogFormVisible = true;
                    this.form = Object.assign({}, response.data.data);
                    if(this.form.categoryIds) {
                        this.categoryIds = []
                        //内容分类,将IDS字符串转换为int数组
                        const categoryIdsStr = this.form.categoryIds.split(',')
                        for(let str of categoryIdsStr) {
                            this.categoryIds.push(parseInt(str))
                        }
                    }
                }
            });
        },
        handleDelete(row) {
            //批量删除数据
            let ids = [];
            if (row.id != undefined) {
                ids.push(row.id);
            } else {
                if (this.multipleSelection.length > 0) {
                    for (let item of this.multipleSelection) {
                        ids.push(item.id);
                    }
                }
            }
            if (ids.length <= 0) {
                this.$notify({
                    title: "提示",
                    message: "请选择需要删除的记录",
                    type: "warning",
                    duration: 2000
                });
            } else {
                this.$confirm("确定要删除？", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(() => {
                        deletedSpecAttr({ idList: ids })
                            .then(response => {
                                if (ResultMessage(response)) {
                                    this.getPage();
                                }
                            })
                            .catch(error => {
                                this.$notify({
                                    title: "提示",
                                    message: "删除失败",
                                    type: "error",
                                    duration: 2000
                                });
                            });
                    })
                    .catch(() => {});
            }
        },
        getData(id) {
            //根据ID查询数据
            this.listLoading = true;
            return selectOneSpecAttr(id)
                .then(response => {
                    if (ResultMessage(response, false)) {
                        this.listLoading = false;
                        return response;
                    } else {
                        this.listLoading = false;
                        return null;
                    }
                })
                .catch(error => {
                    this.$notify({
                        title: "提示",
                        message: "根据ID获取数据失败",
                        type: "error",
                        duration: 2000
                    });
                    this.listLoading = false;
                });
        },
        getPage() {
            //查询分页列表
            this.listLoading = true;
            selectPageAssociationCategoryAndBrandAndType(this.listQuery)
                .then(response => {
                    if (ResultMessage(response, false)) {
                        this.list = response.data.data.list;
                        this.total = parseInt(response.data.data.total);
                        this.listLoading = false;
                    } else {
                        this.listLoading = false;
                    }
                })
                .catch(error => {
                    this.listLoading = false;
                    this.$notify({
                        title: "提示",
                        message: "查询列表失败",
                        type: "error",
                        duration: 2000
                    });
                });
        },
        create(formName) {
            //添加数据
            const set = this.$refs;
            set[formName].validate(valid => {
                if (valid) {
                    createdSpecAttr(this.form)
                        .then(response => {
                            if (ResultMessage(response)) {
                                //this.handleResetFilter();
                            } else {
                                //this.dialogFormVisible = false;
                            }
                        })
                        .catch(error => {
                            this.$notify({
                                title: "提示",
                                message: "添加失败",
                                type: "error",
                                duration: 2000
                            });
                        });
                }
            });
        },
        update(formName) {
            //修改数据
            const set = this.$refs;
            set[formName].validate(valid => {
                if (valid) {
                    updatedSpecAttr(this.form)
                        .then(response => {
                            if (ResultMessage(response)) {
                                this.getPage();
                            }
                            this.dialogFormVisible = false;
                        })
                        .catch(error => {
                            this.$notify({
                                title: "提示",
                                message: "修改失败",
                                type: "error",
                                duration: 2000
                            });
                        });
                }
            });
        },
        cancel(formName) {
            this.dialogFormVisible = false;
            const set = this.$refs;
            set[formName].resetFields();
            this.form = {
                categoryId: this.categoryIds[this.categoryIds.length - 1],
                categoryIds: this.categoryIds.join(','),
                sort: 99
            };
        },
       
        handleSpecVal(row) {
           this.$router.push({path: 'specValue', query: {specId: row.id, name: row.name}})
        },

        /* 获取商品分类 */
        getGoodsCategory() {
            selectTree().then((response) => {
                this.categoryOptions = response.data.data
            })
        },
        handleChangeCascader(value) {
            if(value.length > 0) {
                this.form.categoryId = value[value.length -1]
                this.form.categoryIds = value.join(',')
                this.listQuery.categoryId = value[value.length -1]
            } else {
                this.form.categoryId = null
                this.form.categoryIds = null
                this.listQuery.categoryId = null
            }
        },

        /* 获取商品品牌 */
        getGoodsBrand() {
            selectListBrand().then((response) => {
                this.brandOptions = response.data.data
            })
        },

        /* 获取商品类型 */
        getGoodsType() {
            selectListType().then((response) => {
                this.typeOptions = response.data.data
            })
        }
    }
};
</script>

<!-- 局部样式 -->
<style rel="stylesheet/stylus" lang="stylus" scoped>
    @import './spec.styl'
</style>